package com.xiaoma.tpo.webservice;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiaoma.tpo.domain.ForcastUserScore;
import com.xiaoma.tpo.domain.User;
import com.xiaoma.tpo.dto.ForcastDto;
import com.xiaoma.tpo.dto.ForcastScoreVo;
import com.xiaoma.tpo.dto.ForcastUserScoreDto;
import com.xiaoma.tpo.dto.FrcastQuestionInfoDto;
import com.xiaoma.tpo.service.ForcastQuestionInfoService;
import com.xiaoma.tpo.service.ForcastService;
import com.xiaoma.tpo.service.ForcastUserScoreService;
import com.xiaoma.tpo.service.UserService;
import com.xiaoma.tpo.utils.TPOUtils;
import com.xiaoma.verbal.dao.FctForecastDao;
import com.xiaoma.verbal.domain.FctForecast;
import com.xiaoma.verbal.domain.FctQuestion;
import com.xiaoma.verbal.domain.QuQuestion;

@Controller
@RequestMapping("/service/forcast")
public class ForcastWS {

	@Autowired
	private ForcastService forcastService;
	
	@Autowired
	private ForcastQuestionInfoService forcastQuestionInfoService;
	
	@Autowired
    private UserService userService;
	
	@Autowired
	private ForcastUserScoreService forcastUserScoreService;
	@Autowired
	private FctForecastDao fctForecastDao;
	
	/**
	 * 得到所有的机经预测fitz
	 * @return
	 */
	//旧
	@ResponseBody
	@RequestMapping(value = "/getForcasts")
	public Map<String, Object> getForcast(@RequestHeader String token) {
		
		Map<String, Object> result = new HashMap<String, Object>();
		User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
		List<ForcastDto> list = forcastService.findAllForcast();
		result.put("items", list);
		return result;
	}
	
	/**
	 * 得到机经预测的文本信息
	 * @param forcastId
	 * @return
	 */
	//旧
	@ResponseBody
	@RequestMapping(value = "/getForcastQuestion/{questionId}")
	public Map<String, Object> getForcastQuestion(@RequestHeader String token,
			@PathVariable Integer questionId) {
		
		Map<String, Object> result = new HashMap<String, Object>();
		User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
		List<FrcastQuestionInfoDto> list = forcastQuestionInfoService.findByQuestionId(questionId);
		result.put("items", list);
		return result;
	}
	
	/**
	 * 
	 * 旧的
	 * 
	 * 
	 * 提交分数
	 * @param token
	 * @param userScore
	 * @return
	 */
	//旧
	@RequestMapping(value = "/submitScores/{model}",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> submitScore(@RequestHeader String token,
			@PathVariable Integer model,
			@RequestBody ForcastScoreVo forcastScoreVo) {
		
		Map<String, Object> result = new HashMap<String, Object>();
		User user = userService.findByToken(token);
		if(null == user) {
			result.put("status", -2);
			result.put("message", "invalid token");
			return result;
		}
		if (TPOUtils.isAnonymous(user)) {
			result.put("status", 0);
			result.put("message", "anonymous can't access");
			return result;
		}
		if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
			result.put("status", -1);
			result.put("message", "token disabled over 7 days, please login");
			return result;
		}
		
		Integer userId = user.getId();
		List<ForcastUserScoreDto> userScoreDtos = forcastScoreVo.getScores();
		for(ForcastUserScoreDto scoreDto : userScoreDtos) {
			if(scoreDto.getQuestionId() != null && scoreDto.getQuestionId() != 0) {
				//得到用户该题的得分
				ForcastUserScore score = forcastUserScoreService.findByUserForcast(userId, scoreDto.getQuestionId());
				boolean flag = false;
				if(score != null) {//存在则存大
					if(score.getScore1() < scoreDto.getScore1()) {
						score.setScore1(scoreDto.getScore1());
						flag = true;
					}
					if(score.getScore2() < scoreDto.getScore2()) {
						score.setScore2(scoreDto.getScore2());	
						flag = true;
					}
					if(score.getScore3() < scoreDto.getScore3()) {
						score.setScore3(scoreDto.getScore3());
						flag = true;
					}
				}else {//不存在则新建
					flag = true;
					score = new ForcastUserScore();
					score.setUserId(userId);
					score.setQuestionId(scoreDto.getQuestionId());
					score.setScore1(scoreDto.getScore1());
					score.setScore2(scoreDto.getScore2());
					score.setScore3(scoreDto.getScore3());
				}
				if(flag == true) {
					forcastUserScoreService.saveOrUpdate(score);
				}
			}
		}
		if(model == 1) {//返回所有question的分数
			String groupIds = "(" + forcastScoreVo.getGroupIndex() + ")";
			List<Map<String, Object>> list = forcastUserScoreService.findAllByUser(groupIds,userId);
			result.put("items", list);
		}else {//只负责保存
			result.put("status", 1);
		}
		return result;
	}
	/**
	 ********************************************************************** 
	 */
	/**
	 * 
	 * 新的
	 * 
	 * 
	 * 提交分数
	 * @param token
	 * @param userScore
	 * @return
	 */
	//新
	@RequestMapping(value = "/submitScoresNew/{model}",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> submitScoreNew(@RequestHeader String token,
			@PathVariable Integer model,
			@RequestBody ForcastScoreVo forcastScoreVo) {
		
		Map<String, Object> result = new HashMap<String, Object>();
		User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
        Integer userId = user.getId();
        List<ForcastUserScoreDto> userScoreDtos = forcastScoreVo.getScores();
        for(ForcastUserScoreDto scoreDto : userScoreDtos) {
        	if(scoreDto.getQuestionId() != null && scoreDto.getQuestionId() != 0) {
        		//得到用户该题的得分
        		ForcastUserScore score = forcastUserScoreService.findByUserForcast(userId, scoreDto.getQuestionId());
            	boolean flag = false;
            	if(score != null) {//存在则存大
            		if(score.getScore1() < scoreDto.getScore1()) {
            			score.setScore1(scoreDto.getScore1());
            			flag = true;
            		}
        			if(score.getScore2() < scoreDto.getScore2()) {
        				score.setScore2(scoreDto.getScore2());	
        				flag = true;
            		}
        			if(score.getScore3() < scoreDto.getScore3()) {
        				score.setScore3(scoreDto.getScore3());
        				flag = true;
        			}
            	}else {//不存在则新建
            		flag = true;
            		score = new ForcastUserScore();
            		score.setUserId(userId);
            		score.setQuestionId(scoreDto.getQuestionId());
            		score.setScore1(scoreDto.getScore1());
            		score.setScore2(scoreDto.getScore2());
            		score.setScore3(scoreDto.getScore3());
            	}
            	if(flag == true) {
            		forcastUserScoreService.saveOrUpdate(score);
            	}
        	}
        }
        if(model == 1) {//返回所有question的分数
        	String clsClassId = forcastScoreVo.getGroupIndex();
        	FctForecast fctForecast = new FctForecast();
        	fctForecast.setClsClassId(Integer.parseInt(clsClassId));
        	List<FctForecast> lFctForecasts = fctForecastDao.findByColumns(fctForecast);
        	String groupIds;
        	if(lFctForecasts != null && lFctForecasts.size() > 0){
        		groupIds = "(" + lFctForecasts.get(0).getId() + ")";
        	}else{
        		groupIds = "(" +"0" + ")";
        	}
    		List<Map<String, Object>> list = forcastUserScoreService.findAllByUser(groupIds,userId);
    		result.put("items", list);
    	}else {//只负责保存
    		result.put("status", 1);
    	}
    	return result;
	}
//	@ResponseBody
//	@RequestMapping(value = "/test")
//	public Map<String, Object> test() {
//		Map<String, Object> result = new HashMap<String, Object>();
//		String groupIds = "(10,12,4)";
//		List<Map<String, Object>> list = forcastUserScoreService.findAllByUser(groupIds,1);
//		return result;
//	}
	
	/**
	 * 得到所有的机经预测问题ID 新的
	 * @return
	 */
	//新的
	@ResponseBody
	@RequestMapping(value = "/getTheForcast",method=RequestMethod.GET)
	public Map<String, Object> getTheForcast(@RequestHeader String token,@RequestParam Integer id) {
		
		Map<String, Object> result = new HashMap<String, Object>();
		User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
		List<FctQuestion> list = forcastService.findAllForcastNew(id);
		result.put("items", list);
		return result;
	}
	/**
	 * 得到某个问题 和 旗下的答案 新的
	 * @param forcastId
	 * @return
	 */
	//新的
	@RequestMapping(value = "/getForcastQuestionNew/{questionId}",method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getForcastQuestionNew(@RequestHeader String token,
			@PathVariable Integer questionId) {
		
		Map<String, Object> result = new HashMap<String, Object>();
		User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
        List<Object> list = forcastQuestionInfoService.findByQuestionIdNew(questionId);
        List<QuQuestion> lQuQuestions = (List<QuQuestion>)list.get(0);
        result.put("question", lQuQuestions.get(0));
		result.put("answer", list.get(1));
		return result;
	}
	
}
